$NG.AllReady(function (page, { useDataIndexChange, useValuesChange, useUpdateRows, useClick, useBeforeClick }) {
    const mstform = $NG.getCmpApi("p_form_fact_outout_value_m");
    const grid = $NG.getCmpApi("p_form_fact_outout_value_d");


    {//初始化逻辑BEGIN
        if (mstform) {
            console.log(mstform.name + ' is ready');
            PCFilter();
        } else {
            console.error('mstform is not available');
        };
    }//初始化逻辑END


    if (page.oType == "add") {
        var pc = mstform.getItem("phid_pc")
        var dt = mstform.getItem("bill_dt")
        var u_plan_type = mstform.getItem("u_plan_type")

        mstform.getItem("u_total_sum").setValue('0')
        mstform.getItem("u_kg_sum").setValue('0')

        console.log('123123');
        if (pc.getValue() > '0') {
            Czqd(pc.getValue())
            PCFilter();
        }
        getTjzq(dt.getValue())

        u_plan_type.setValue('01')
    }
    if (page.oType == "add" || page.oType == "edit") {
        { //添加按钮
            // $NG.getCmpApi('toolbar_p_form_fact_outout_value_d').insert({
            //     id: "czadd",
            //     text: "引用深化设计清单内容",
            //     iconCls: "icon-New"
            // });

            // $NG.getCmpApi('toolbar_p_form_fact_outout_value_d').insert({
            //     id: "czsbqd",
            //     text: "引用设备清单内容",
            //     iconCls: "icon-New"
            // });
        }
    }
    page.oType == 'add' && getPtInfoByPhid()
    function getPtInfoByPhid() {
		if (mstform.getItem("phid_pc").getValue()) {
			$NG.execServer(
				"getPtInfoByPhid",
				{ phid: mstform.getItem("phid_pc").getValue() },
				function (res) {
					const datas = JSON.parse(res.data)[0].extendObjects;
					console.log(`获取项目信息`,datas);
					//帮助字段赋值
					$NG.updateState((updater) => {
						updater.data.p_form_fact_outout_value_m.setProps({
							u_pc_ywlx:{
                                label:datas.ywlx_name,
                                value:datas.user_ywlx
                            }
						});
                        setTimeout(()=>{
                            hideBtn()
                        },300)
					});
				}
			);
		}
	}
    useClick(async function ({ args }) {
        // 获取表单中 phid_pc 的值
        const phidPcValue = mstform.getItem("phid_pc").getValue();

        // 假设 grid 是你的表格组件，并且已经加载了数据
        let gridData = grid.getRows(); // 获取 grid 中的所有行数据

        // 从 grid 数据中提取 u_shsj_name 字段的值
        let existingItems = gridData.map(row => row.u_shsj_name); // 提取所有已有的 u_shsj_name

        // 构建过滤条件字符串，假设使用 SQL IN 操作符进行过滤
        let filterCondition = existingItems.length > 0
            ? `m.phid_pc = '${phidPcValue}' AND d.u_equipment_item NOT IN ('${existingItems.join("','")}')`
            : `m.phid_pc = '${phidPcValue}'`;

        // 打开帮助选择器并应用过滤条件
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",
            helpId: "cz_shsjqd",
            valueField: "u_equipment_item",
            labelField: "u_equipment_list_name",
            clientSqlFilter: filterCondition // 应用过滤条件
        }).then((data) => {
            console.log(data);

            var gridArr = []; // 初始化 gridArr 数组
            for (var i = 0; i < data.length; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {
                    u_shsj_no: '',
                    u_shsj_name: '',
                    u_detailed_qty: '',
                    u_model: '',
                    u_tech_params: '',
                    u_cnt_qty: '',
                    u_unit: '',
                    prc: '',
                    taxrate: '',
                    u_ly: '',
                    u_srlx: '',
                    u_nfbsl: '',
              
                };
                // 对表体字段进行赋值, 可以取数据库中的值进行赋值
                gridObj.u_srlx = data[i].origin.u_revenue_type;
                gridObj.u_srlx_EXName = data[i].origin.c_name;
                gridObj.u_shsj_no = data[i].origin.u_equipment_list_no;
                gridObj.u_shsj_name = data[i].origin.u_equipment_item;
                gridObj.u_shsj_name_EXName = data[i].origin.u_equipment_list_name;
                gridObj.u_detailed_qty = data[i].origin.u_u_total_shsj;
                gridObj.u_model = data[i].origin.u_spec;
                gridObj.u_tech_params = data[i].origin.u_tech_params;
                gridObj.u_cnt_qty = data[i].origin.u_cnt_qty;
                gridObj.u_unit = data[i].origin.u_msunit;
                gridObj.u_unit_EXName = data[i].origin.msname;
                gridObj.prc = data[i].origin.u_cnt_prc;
                gridObj.taxrate = data[i].origin.u_cnt_item_tax_rate ;
                gridObj.u_nfbsl = data[i].origin.qdsl;
                gridObj.u_kg_qty = data[i].origin.kglj_qty;
                gridObj.u_kg_amt = data[i].origin.kgljje;
                gridObj.u_year_amt = data[i].origin.nlje;
                gridObj.u_year_qty = data[i].origin.nl_qty;

                gridObj.u_ly = '深化设计清单手工选择';

                // 关键步骤：将 gridObj 添加到 gridArr 数组中
                gridArr.push(gridObj);
            }
            console.log(gridArr); // 确保这里打印出来的 gridArr 不是空的
            grid.addRows(gridArr); // 将数据添加到表格组件中
        });
    }, "czadd");

    useClick(async function ({ args }) {
        // 获取表单中 phid_pc 的值
        const phidPcValue = mstform.getItem("phid_pc").getValue();

        // 假设 grid 是你的表格组件，并且已经加载了数据
        let gridData = grid.getRows(); // 获取 grid 中的所有行数据

        // 从 grid 数据中提取 u_shsj_name 字段的值
        let existingItems = gridData.map(row => row.u_shsj_name); // 提取所有已有的 u_shsj_name

        // 构建过滤条件字符串，假设使用 SQL IN 操作符进行过滤
        let filterCondition = existingItems.length > 0
            ? `m.phid_pc = '${phidPcValue}' AND d.phid NOT IN ('${existingItems.join("','")}')`
            : `m.phid_pc = '${phidPcValue}'`;

        // 打开帮助选择器并应用过滤条件
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",
            helpId: "cz_sbqd",
            valueField: "phid",
            labelField: "u_equipment_list_name",
            clientSqlFilter: filterCondition // 应用过滤条件
        }).then((data) => {
            console.log(data);

            var gridArr = []; // 初始化 gridArr 数组
            for (var i = 0; i < data.length; i++) {
                // 列出需要赋值的表体字段
                var gridObj = {
                    u_shsj_no: '',
                    u_shsj_name: '',
                    u_detailed_qty: '',
                    u_model: '',
                    u_tech_params: '',
                    u_cnt_qty: '',
                    u_unit: '',
                    prc: '',
                    taxrate: '',
                    u_ly: '',
                    u_srlx: '',
                    u_nfbsl: '',
              
                };
                // 对表体字段进行赋值, 可以取数据库中的值进行赋值
                gridObj.u_srlx = data[i].origin.u_revenue_type;
                gridObj.u_srlx_EXName = data[i].origin.c_name;
                gridObj.u_shsj_no = data[i].origin.u_equipment_list_no;
                gridObj.u_shsj_name = data[i].origin.u_equipment_item;
                gridObj.u_shsj_name_EXName = data[i].origin.u_equipment_list_name;
                gridObj.u_detailed_qty = data[i].origin.u_qty;
                gridObj.u_model = data[i].origin.u_cnt_d_spec;
                gridObj.u_tech_params = data[i].origin.u_desc;
                gridObj.u_cnt_qty = data[i].origin.u_qty;
                gridObj.u_unit = data[i].origin.u_unit;
                gridObj.u_unit_EXName = data[i].origin.msname;
                gridObj.prc = data[i].origin.u_cnt_prc;
                gridObj.taxrate = data[i].origin.u_cnt_d_taxrate;
                gridObj.u_nfbsl = data[i].origin.qdsl;
                gridObj.u_kg_qty = data[i].origin.kglj_qty;
                gridObj.u_kg_amt = data[i].origin.kgljje;
                gridObj.u_year_amt = data[i].origin.nlje;
                gridObj.u_year_qty = data[i].origin.nl_qty;

                gridObj.u_ly = '设备清单手工选择';

                // 关键步骤：将 gridObj 添加到 gridArr 数组中
                gridArr.push(gridObj);
            }
            console.log(gridArr); // 确保这里打印出来的 gridArr 不是空的
            grid.addRows(gridArr); // 将数据添加到表格组件中
        });
    }, "czsbqd");


    //项目名称变化时自动带入产品线、事业部等
    useValuesChange(({ args }) => {
        console.log(args[0]);
        //const phid_pc = args[0].pc.PhId;
        const pc = args[0].phid_pc.value;
        //从项目取值
        if (pc) {
            console.log(pc);
            Czqd(pc)

        }
        setTimeout(()=>{
            hideBtn()
        },300)
        PCFilter();
        getPtInfoByPhid()
    }, "p_form_fact_outout_value_m.phid_pc");

    useValuesChange(({ args }) => {
        hideBtn()
    }, "p_form_fact_outout_value_m.u_pc_ywlx");


    useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)
        if (record.u_con_qty > record.u_detailed_qty) {
            $NG.alert('完成数量不能大于深化设计数量');
            record.u_con_qty = 0
        } 
        else if ((record.u_kg_qty+record.u_con_qty)> record.u_detailed_qty) {
            $NG.alert('累计完成数量不能大于深化设计数量,剩余数量为',parseFloat(record.u_detailed_qty-record.u_kg_qty));
  
            record.u_con_qty = 0
        }
        else {
            record.u_con_sp = record.u_con_qty
            record.u_con_amt = record.prc * record.u_con_qty / record.u_nfbsl * record.u_cnt_qty*(1+record.taxrate)
            record.u_con_zb = record.u_con_sp / record.u_con_qty
            record.u_con_spcz = record.u_con_qty * record.prc / record.u_nfbsl * record.u_cnt_qty*(1+record.taxrate)
            record.u_year_qty_hbc = (record.u_year_qty ?? 0) + record.u_con_qty
            record.u_year_amt_hbc = (record.u_year_amt ?? 0) + record.u_con_qty * record.prc*(1+record.taxrate) / record.u_nfbsl * record.u_cnt_qty
            record.u_kg_qty_hbc = (record.u_kg_qty ?? 0) + record.u_con_qty
            record.u_kg_amt_hbc = (record.u_kg_amt ?? 0)+ record.u_con_qty * record.prc*(1+record.taxrate) / record.u_nfbsl * record.u_cnt_qty

        }

        grid.updateRow(args[0]);
    }, "u_con_qty");


    useDataIndexChange(({ args }) => {
        const record = args[0];
        console.log(record)

        if (record.u_con_sp > record.u_con_qty) {
            $NG.alert('审批数量不能大于完成数量');
            record.u_con_sp = record.u_con_qty
        }
        else {

            record.u_con_zb = record.u_con_sp / record.u_con_qty
            record.u_con_spcz = record.prc*(1+record.taxrate) * record.u_con_sp / record.u_nfbsl * record.u_cnt_qty

            record.u_year_qty_hbc = (record.u_year_qty ?? 0) + record.u_con_sp
            record.u_year_amt_hbc = (record.u_year_amt ?? 0) + (record.prc*(1+record.taxrate) * record.u_con_sp / record.u_nfbsl * record.u_cnt_qty)
            record.u_kg_qty_hbc = (record.u_kg_qty ?? 0)+ record.u_con_sp
            record.u_kg_amt_hbc = (record.u_kg_amt ?? 0) + (record.prc*(1+record.taxrate) * record.u_con_sp / record.u_nfbsl * record.u_cnt_qty)

        }
        grid.updateRow(args[0]);
    }, "u_con_sp");


    useUpdateRows(({ args, table }) => {
        // const u_jzbcby_amt = mstform.getItem("u_jzbcby_amt").getValue(); //获取值
        // const u_jzbcby_amt_vat = mstform.getItem("u_jzbcby_amt_vat").getValue(); //获取值
        // const amt = mstform.getItem("amt").getValue(); //获取值
        var sumAmt = 0;
        const rows = args[0];
        rows.forEach((items) => {
            if (items.u_con_spcz) {
                sumAmt += parseFloat(items.u_con_spcz);  //明细
            }
            //汇总赋值到表头字段
            $NG.updateState((updater) => {
                updater.data.p_form_fact_outout_value_m.setProps({
                    u_amt_sum: sumAmt,
                    u_kc_hbc: sumAmt+mstform.getItem("u_total_sum").getValue(),
                    u_nl_hbc: sumAmt+mstform.getItem("u_kg_sum").getValue(),
                });
            });

        });
        grid.updateRow(rows);
    }, 'p_form_fact_outout_value_d');

    function hideBtn(){
        const gridt = $NG.getCmpApi("toolbar_p_form_fact_outout_value_d")
        let lock = true
        if(mstform.getItem("u_pc_ywlx").getValue()=='8570000000000350'){
            lock = false
        } else {
            lock = true
        }
        if(!lock){
            gridt.hideButton("czadd")
            $NG.getCmpApi('toolbar_p_form_fact_outout_value_d').insert({
                id: "czsbqd",
                text: "引用设备清单内容",
                iconCls: "icon-New"
            });
        } else {
            gridt.hideButton("czsbqd")
            $NG.getCmpApi('toolbar_p_form_fact_outout_value_d').insert({
                id: "czadd",
                text: "引用深化设计清单内容",
                iconCls: "icon-New"
            });
        }
    }
});


//合同根据项目ID过滤
function PCFilter() {
    $NG.updateUI((updater, state) => {
        console.log('过滤参数检查', updater);
        updater.fieldSetForm.p_form_fact_outout_value_m.u_cnt_name.setProps({
            onBeforeOpen: async () => {
                var phid_pc = $NG.getCmpApi('p_form_fact_outout_value_m').getItem('phid_pc').getValue();
                if (!phid_pc) {
                    $NG.alert("请先选择项目");
                    return false;
                } else {
                    return true;
                }
            },
            ...(!!$NG.getCmpApi('p_form_fact_outout_value_m').getItem('phid_pc').getValue() && {
                clientSqlFilter: {
                    phid_pc: $NG.getCmpApi('p_form_fact_outout_value_m').getItem('phid_pc').getValue()
                }
            }),
        });
    });
}



function Czqd(pcvalue) {

    const mstform = $NG.getCmpApi("p_form_fact_outout_value_m");
    const grid = $NG.getCmpApi("p_form_fact_outout_value_d");

    var pcname = mstform.getItem("phid_pc").getRawValue().label
    var cycle = mstform.getItem("phid_cycle").getRawValue().label
    $NG.updateState((updater) => {
        updater.data.p_form_fact_outout_value_m.setProps({
            bill_name: pcname + cycle + "产值填报",

        });
    });


    grid.clearRows();



    $NG.execServer("GetCzLjInfo", { pc: pcvalue }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        const cz_klje = data[0].extendObjects.cz_klje;
        const cz_nlje = data[0].extendObjects.cz_nlje;
        console.log('执行到这儿了啊啊啊啊啊啊')
        console.log(res.count)
        //项目类型
        if (res.count > 0) {
            $NG.updateState((updater) => {
                updater.data.p_form_fact_outout_value_m.setProps({
                    u_total_sum: cz_nlje,
                    u_kg_sum: cz_klje,

                });
            });
        }
        else {
            $NG.updateState((updater) => {
                updater.data.p_form_fact_outout_value_m.setProps({
                    u_total_sum: 0,
                    u_kg_sum: 0,
                 

                });
            });

        }
    });


    $NG.execServer("CzGetCntInfo", { pc: pcvalue }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        const cntid = data[0].extendObjects.cntid;
        const cntname = data[0].extendObjects.cntname;

        //项目类型
        $NG.updateState((updater) => {
            updater.data.p_form_fact_outout_value_m.setProps({
                u_cnt_name: {
                    //帮助需要赋两个值value、label
                    value: cntid,
                    label: cntname,
                },

            });
        });
    });


    $NG.execServer('GetCzQd', { pc: pcvalue }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);

        var gridArr = []; // 定义表体数组
        var gridCount = res.count; // 增加的行数, 可根据从数据库中取出的数据总数增行
        for (var i = 0; i < gridCount; i++) {
            // 列出需要赋值的表体字段
            var gridObj = {
                u_shsj_no: '',
                u_shsj_name: '',
                u_detailed_qty: '',
                u_model: '',
                u_tech_params: '',
                u_cnt_qty: '',
                u_unit: '',
                prc: '',
                u_con_qty: '',
                u_con_amt: '',
                u_con_sp: '',
                u_con_spcz: '',
                // u_nexplan_qty: '',
                // u_nexplan_amt:'',
                // u_nxplan_qtyzb: '',
                u_year_qty: '',
                u_year_amt: '',
                u_kg_qty: '',
                u_kg_amt: '',
                u_srlx: '',
                taxrate: '',
                u_ly: '',
                u_nfbsl: '',
                u_year_qty_hbc: '',
                u_year_amt_hbc: '',
                u_kg_qty_hbc: '',
                u_kg_amt_hbc: '',
            };
            // 对表体字段进行赋值, 可以取数据库中的值进行赋值
            // 确保这些字段为空时赋值为 0
            const rest_qty = data[i].extendObjects.rest_qty;
            const cz_klje = data[i].extendObjects.cz_klje ?? 0;
            const czsl_year_total = data[i].extendObjects.czsl_year_total ?? 0;
            const czje_year_total = data[i].extendObjects.czje_year_total ?? 0;
            const cz_klsl = data[i].extendObjects.cz_klsl ?? 0;

            // 其他字段赋值
            gridObj.u_shsj_no = data[i].extendObjects.sbqd_no || "";

            gridObj.u_srlx = data[i].extendObjects.u_revenue_type || "";
            gridObj.u_srlx_EXName = data[i].extendObjects.srlx_name || "";
            gridObj.u_shsj_name = data[i].extendObjects.sbqdid || "";
            gridObj.u_shsj_name_EXName = data[i].extendObjects.sbqd_name || "";
            gridObj.u_detailed_qty = data[i].extendObjects.sh_qty ?? 0;
            gridObj.u_model = data[i].extendObjects.spec || "";
            gridObj.u_tech_params = data[i].extendObjects.jscs || "";
            gridObj.u_cnt_qty = data[i].extendObjects.ht_qty ?? 0;
            gridObj.u_unit = data[i].extendObjects.msunit || "";
            gridObj.u_unit_EXName = data[i].extendObjects.msname || "";
            gridObj.prc = data[i].extendObjects.prc ?? 0;
            gridObj.u_nfbsl = data[i].extendObjects.qdsl;
            // 计算字段
            gridObj.u_con_qty = rest_qty;
            gridObj.u_con_amt = data[i].extendObjects.prc*(1+data[i].extendObjects.taxrate) * (rest_qty / data[i].extendObjects.qdsl) * data[i].extendObjects.ht_qty;
            gridObj.u_con_sp = rest_qty;
            gridObj.taxrate = data[i].extendObjects.taxrate || 0;
            gridObj.u_con_spcz = data[i].extendObjects.prc*(1+data[i].extendObjects.taxrate) * (rest_qty / data[i].extendObjects.qdsl) * data[i].extendObjects.ht_qty;
            gridObj.u_con_zb = rest_qty !== 0 ? rest_qty / rest_qty : 0; // 避免除零错误

            gridObj.u_year_qty = czsl_year_total;
            gridObj.u_year_amt = czje_year_total;
            gridObj.u_kg_qty = cz_klsl;
            gridObj.u_kg_amt = cz_klje;
            gridObj.u_ly = data[i].extendObjects.ly || "";

            gridObj.u_year_qty_hbc = czsl_year_total + rest_qty;
            gridObj.u_year_amt_hbc = czje_year_total + data[i].extendObjects.prc*(1+data[i].extendObjects.taxrate) * (rest_qty / data[i].extendObjects.qdsl) * data[i].extendObjects.ht_qty
            gridObj.u_kg_qty_hbc = cz_klsl + rest_qty;
            gridObj.u_kg_amt_hbc = cz_klje + data[i].extendObjects.prc *(1+data[i].extendObjects.taxrate)* (rest_qty / data[i].extendObjects.qdsl) * data[i].extendObjects.ht_qty;
            gridArr.push(gridObj);
        }

        // 清空表格内容（放在循环外部）
        grid.clearRows();

        // 调用新增表体行数据的函数
        grid.addRows(gridArr);

        // 更新RichHelp字段（如果需要）
        // 这里假设有一个方法可以刷新或重新渲染表格，以确保RichHelp字段正确显示
        grid.refreshView(); // 或者使用grid.refreshData();
    });

}
function getTjzq(dt) {

    $NG.execServer("GetTjzq", { dt: dt }, function (res) {
        if (res.count == 0) return;
        const data = JSON.parse(res.data);
        const phid = data[0].extendObjects.phid;
        const bill_name = data[0].extendObjects.bill_name;
        //项目类型
        $NG.updateState((updater) => {
            updater.data.p_form_fact_outout_value_m.setProps({
                phid_cycle: {
                    //帮助需要赋两个值value、label
                    value: phid,
                    label: bill_name,
                },

            });
        });
    });
}